package com.springboot_gradrecruit.controller;

import com.baomidou.mybatisplus.core.toolkit.ClassUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.springboot_gradrecruit.common.NonStaticResourceHttpRequestHandler;
import com.springboot_gradrecruit.common.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @author zr
 * 视频文件管理
 */
@Tag(name = "视频文件管理相关接口")
@RestController
@RequestMapping("/video-file")
@Slf4j
public class VideoFileController {

    private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    @Value("${uploadLocation.path-video}")
    private String uploadPath;

    public VideoFileController(NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler) {
        this.nonStaticResourceHttpRequestHandler = nonStaticResourceHttpRequestHandler;
    }


    //1.上传视频
    @Operation(summary = "上传视频")
    @PostMapping("/video-upload")
    public R<String> uploadVideo(MultipartFile file) throws IOException {
        log.info("视频上传开始");
        //file是一个临时文件，需要转存的指定位置，否则本次请求完成后临时文件会删除

        //获得原始文件名
        String originalFilenameVideo = file.getOriginalFilename();

        //TODO:使用uuid重新生成文件名，防止文件名重复，造成文件覆盖
        String suffix = originalFilenameVideo.substring(originalFilenameVideo.lastIndexOf("."));
        String fileName = UUID.randomUUID() + suffix;

        //创建文件对象
//        String uploadPath = "D:\\update\\video\\";
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            //目录不存在，创建目录
            dir.mkdirs();
        }

        //将临时文件转存到指定位置
        file.transferTo(new File(uploadPath + fileName));
        log.info("视频上传成功");
        return R.success(fileName, "上传成功");
    }


    //2.播放视频
    @Operation(summary = "播放视频")
    @GetMapping("/video")
    public void videoPreview(String videoName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("videoName:"+videoName);

        //假如我把视频1.mp4放在了static下的video文件夹里面
        //sourcePath 是获取resources文件夹的绝对地址
        //realPath 即是视频所在的磁盘地址
        String sourcePath = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1);
//        String realPath = uploadPath +"/1.mp4";
        String realPath = uploadPath +videoName;


        Path filePath = Paths.get(realPath );
        if (Files.exists(filePath)) {
            String mimeType = Files.probeContentType(filePath);
            if (!StringUtils.isEmpty(mimeType)) {
                response.setContentType(mimeType);
            }
            request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }

}